package com.qumitech.visualnovel.component.util;


import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * ExcelUtil 工具
 * @author jlyin
 * @date 2019/1/11 19:20
 */
public class ExcelUtil {
    private final static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    public static Map<Integer, Map<Integer, Object>> readExcelContentz(MultipartFile file) throws Exception {

        Map<Integer, Map<Integer, Object>> content = new HashMap<>(16);
        // 上传文件名
        Workbook wb = getWb(file);
        if (wb == null) {
            throw new Exception("Workbook对象为空！");
        }
        Sheet sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        Row row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            Map<Integer, Object> cellValue = new HashMap<>(16);
            while (j < colNum) {
                Object obj = getCellFormatValue(row.getCell(j));
                cellValue.put(j, obj);
                j++;
            }
            content.put(i, cellValue);
        }

        return content;
    }

    private static Object getCellFormatValue(Cell cell) {
        Object cellValue = "";
        if (cell != null) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                case Cell.CELL_TYPE_FORMULA: {
                    if (DateUtil.isCellDateFormatted(cell)) {
                        cellValue = cell.getDateCellValue();
                    } else {
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                default:
            }
        }
        return cellValue;
    }

    private static Workbook getWb(MultipartFile mf) {
        Workbook wb = null;
        try {
            InputStream is  = mf.getInputStream();
            try {
                try {
                    wb = WorkbookFactory.create(is);
                } catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
                    e.printStackTrace();
                }
            } catch (InvalidFormatException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            logger.error("IOException", e);
        }
        return wb;
    }
}
